import { CreateHandleTo, IHandle, RemoveHandle } from "../../data/data-handle";
import { CreateUIButton, IUIButtonOptions, UIButton } from "../control/ui-button";
import { AbstractScrollList, IAbstractScrollListOptions } from "./abstract-scroll-list";
import { Scene } from "@babylonjs/core/scene";
import { Mesh } from "@babylonjs/core/Meshes/mesh";


/**
 * 滚动条容器按钮组件参数对象
 */
interface IUIScrollButtonListOptions extends IAbstractScrollListOptions { }

/**
 * 滚动条容器按钮组件
 * @param name 名称
 * @param scene 所在场景
 * @param options 参数对象
 */
class UIScrollButtonList extends AbstractScrollList<UIButton, IUIButtonOptions>{

    private _clickHandles: IHandle<string>[] = [];

    constructor(name: string, scene: Scene, options?: IUIScrollButtonListOptions) {
        super(name, scene, options);
        this.updateBlockSize();
    }

    /**
     * 添加点击时的回调函数对象
     * @param func 回调函数
     * @returns 回调函数对象
     */
    public onClick(func: { (name: string): void }): IHandle<string> {
        return CreateHandleTo<string>(func, this._clickHandles);
    }

    /**
     * 移除点击回调函数对象
     * @param handle 回调函数对象或其id
     */
    public removeClickHandle(handle: number | IHandle<string>): void {
        RemoveHandle(handle, this._clickHandles);
    }

    protected generateMember(name: string, options?: IUIButtonOptions | undefined): UIButton {
        const ops = options || {};
        ops.cornerRadius = ops.cornerRadius || 5;
        ops.text = ops.text || name;
        ops.background = ops.background || '#000000';
        ops.enabledStyle = (enabled, scope) => {
            const scp = scope as UIButton;
            scp.control.disabledColor = ops.background || '#000000';
            if (enabled) {
                (scp.container as Mesh).visibility = 1;
            } else {
                (scp.container as Mesh).visibility = 0.2;
            }
        };

        return CreateUIButton(name, this.scene, ops, () => {
            this._clickHandles.forEach(handle => handle.callback(name));
        });
    }

}

/**
 * 创建滚动条容器按钮组件
 * @param name 名称
 * @param scene 所在场景
 * @param options 参数对象
 * @param items 成员名称及参数对象
 * @param callback 回调函数
 * @returns 创建的组件
 */
const CreateUIScrollButtonList = (name: string, scene: Scene, options: IUIScrollButtonListOptions, items: Array<{ name: string, option?: IUIButtonOptions }>, callback?: { (name: string): void }): UIScrollButtonList => {
    const sb = new UIScrollButtonList(name, scene, options);
    for (const item of items) {
        sb.add(item.name, item.option);
    }
    if (callback) sb.onClick(callback);
    return sb;
};


export { UIScrollButtonList, CreateUIScrollButtonList };
export type { IUIScrollButtonListOptions };